package com.sosee.cgfw.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;

import com.amap.api.navi.model.NaviLatLng;
import com.sosee.cgfw.entity.BrandJson;
import com.sosee.cgfw.entity.Data;
import com.sosee.cgfw.entity.JsonData;
import com.sosee.cgfw.entity.News;
import com.sosee.cgfw.entity.PiaoJiaData;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import net.sourceforge.pinyin4j.PinyinHelper;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by Thinkpad on 2016/1/25.
 * 工具类
 */
public class Utils {
    //是否显示测试土司    测试环境下打开  上线版本关闭
    public static boolean isTest=true;

    public Utils(Context mContext){
        context=mContext;
    }
    public static List<String> list_menu=new ArrayList<String>();//需要展开的菜单项（活动日程中）
    public static List<String> list_shoucang=new ArrayList<String>();//存储已收藏的活动id
    public static List<String> list_date=new ArrayList<String>();//活动日程  日期集合

    public static NaviLatLng eNlat;//导航终点
    public static List<String> pinList=new ArrayList<String>();//品牌地址集合
    public static List<String> letterList=new ArrayList<String>();//品牌首字母集
    public static Map<String,BrandJson> bran_list=new HashMap<String, BrandJson>();
    public static int day=0;//记录 智能助理选中的  日期位置
    public static int position=0;//记录我的票夹中选中日期的位置
    public static List<PiaoJiaData> piaoJiaList=new ArrayList<PiaoJiaData>();//向邀请函activity 传递的数据
    public static List<PiaoJiaData> shenQingList=new ArrayList<PiaoJiaData>();//向票夹 内 申请 activity 传递的数据
    public static Data data;//由我的票夹 activity 向 票夹详情activity传递数据



    //解析新闻json  获取资讯列表
    public static Context context;
    public static List<News> getNewsFromJson(String json){
        List<News> list=new ArrayList<News>();
        try {
            JSONArray jsonArray=new JSONArray(json);
            for (int i=0;i<jsonArray.length();i++){
                JSONObject jsonObject=jsonArray.getJSONObject(i);
                JSONObject data=jsonObject.getJSONObject("data");
                News news=new News();
                news.setAbstrac(data.getString("abstract"));
                news.setDate(data.getString("date"));
                news.setTitle(data.getString("title"));
                news.setLink(data.getString("link"));
                news.setPic(data.getString("pic"));
                list.add(news);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 为图片加上边框
     * @param src 边框图片
     * @param logo 原图片
     */
    public static Bitmap addFrame(Bitmap src, Bitmap logo) {
        if (src == null) {
            return null;
        }

        if (logo == null) {
            return src;
        }

        //获取图片的宽高
        int srcWidth = src.getWidth();
        int srcHeight = src.getHeight();
        int logoWidth = logo.getWidth();
        int logoHeight = logo.getHeight();

        if (srcWidth == 0 || srcHeight == 0) {
            return null;
        }

        if (logoWidth == 0 || logoHeight == 0) {
            return src;
        }

        //logo大小为二维码整体大小的1/5
        float scaleFactor = srcWidth * 1.0f / 5 / logoWidth*4;
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(src, 0, 0, null);
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);

            canvas.save(Canvas.ALL_SAVE_FLAG);
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }

        return bitmap;
    }
    //土司
    public static void showToast(String text){
        Toast.makeText(context,text,Toast.LENGTH_SHORT).show();

    }
    //长土司
    public static void showToastLong(String text){
        Toast.makeText(context,text,Toast.LENGTH_LONG).show();
    }
    //测试土司
    public static void showToast_test(String text){
        if(isTest){
            Toast.makeText(context,text,Toast.LENGTH_SHORT).show();
        }
    }

    //旋转图片
    public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;

        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
            LogUtils.log_E("utilszhong fangf :"+e.toString());
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }


    //解析活动日程json
    public static List<JsonData> getSchedule(String json){

        LogUtils.log_E("日程json：====" + json);
        List<JsonData> list=com.alibaba.fastjson.JSONArray.parseArray(json, JsonData.class);
       return list;
    }
    //将字符串按照一定方式切割为list
    public static List<String> stringToList(String s,String divider){
        List<String> slist=new ArrayList<String>();
        String[] arr=s.split(divider);
        for (int i=0;i<arr.length;i++){
            slist.add(arr[i]);
        }

        return slist;
    }
    //将list转化为字符串
    public static String listToString(List<String> list,String split){
        String s="";
        for (int i=0;i<list.size();i++){
            if(i>0){
                s+=split;
            }
            s+=list.get(i);
        }
        return s;
    }
    static String[] wee=new String[]{"日","一","二","三","四","五","六"};
    public static List<Calendar> dayList=new ArrayList<Calendar>();
    //生成日期选择器的day集合
    public static List<String> getTime(){
        dayList.clear();
        List<Calendar> tdlist=new ArrayList<Calendar>();
        List<Calendar> zdlist=new ArrayList<Calendar>();
        List<String> tlist=new ArrayList<String>();
        Date nowTime = new Date(); // 要转换的时间
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(nowTime.getTime());
        List<String> temList=new ArrayList<String>();
        List<String> zList=new ArrayList<String>();
        for (int i=0;i<10;i++){
            cal.add(Calendar.DAY_OF_YEAR, +1);
            String s=cal.getTime().toString();
            int month=cal.get(Calendar.MONTH)+1;
            int day=cal.get(Calendar.DAY_OF_MONTH);
            int week=cal.get(Calendar.DAY_OF_WEEK)-1;
            LogUtils.log_E("中文日期"+month+"月"+day+"日"+"周"+week);
            String[] arr=s.split(" ");
            s=month+"月"+day+"号"+"周"+wee[week];
            zList.add(s);
//            LogUtils.log_E(s);
            zdlist.add(cal);
        }

        cal.add(Calendar.DAY_OF_YEAR, -21);
        for (int i=0;i<10;i++){
            cal.add(Calendar.DAY_OF_YEAR,+1);
            String s=cal.getTime().toString();
            int month=cal.get(Calendar.MONTH)+1;
            int day=cal.get(Calendar.DAY_OF_MONTH);
            int week=cal.get(Calendar.DAY_OF_WEEK)-1;
            LogUtils.log_E("中文日期"+month+"月"+day+"日"+"周"+week);
            s=month+"月"+day+"号"+"周"+wee[week];
            temList.add(s);
            tdlist.add(cal);

//            LogUtils.log_E("s:===="+s);
        }
        tlist.addAll(temList);
        dayList.addAll(tdlist);
        Date ntim = new Date(); // 要转换的时间
        Calendar today = Calendar.getInstance();
        cal.setTimeInMillis(ntim.getTime());
        tlist.add("Today");
        tlist.addAll(zList);
        dayList.add(today);
        dayList.addAll(zdlist);

        for (String n:tlist){
            LogUtils.log_E(n);
        }

        return tlist;
    }

    public static String getDate(int year,int mon,int da){
        String s="";
        Calendar ca=Calendar.getInstance();
        ca.set(year, mon - 1, da);
        int month=ca.get(Calendar.MONTH)+1;
        int day=ca.get(Calendar.DAY_OF_MONTH);
        int week=ca.get(Calendar.DAY_OF_WEEK)-1;
        s=month+"月"+day+"日"+"周"+wee[week];
        return s;
    }



    /**
     * 提取每个汉字的首字母
     *
     * @param str
     * @return String
     */
    public static String getPinYinHeadChar(String str) {
        String convert = "";
            if(str!=null&&str.length()>0){
                char word = str.charAt(0);
                // 提取汉字的首字母
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
                if (pinyinArray != null) {
                    convert += pinyinArray[0].charAt(0);
                } else {
                    convert += word;
                }
            }


        LogUtils.log_E("首字母：" + convert);
        return convert.toUpperCase();
    }
    //对map 按照key 排序
    public static List<List<String>> sortMap(Map<String,List<String>> map){
        List<List<String>> nMap=new ArrayList<List<String>>();
        Iterator<String> it=map.keySet().iterator();
        List<String> key_List=new ArrayList<String>();
        while (it.hasNext()){
            key_List.add(it.next());
        }
        Collections.sort(key_List);
        for (String s:key_List){
            nMap.add(map.get(s));
            LogUtils.log_E("=="+s);
        }
        return nMap;
    }



    /**
     * 根据提供的字符串,生成相应的二维码位图对象
     * @param text 字符串
     * @param QR_WIDTH 位图宽度
     * @param QR_HEIGHT 位图高度
     * @return 二维码位图对象
     */
    public static Bitmap createQRImage(
            String text, int QR_WIDTH,int QR_HEIGHT) {

        Bitmap bitmap = null;
        try {
            // 需要引入core包
            QRCodeWriter writer = new QRCodeWriter();
            // 获取文本内容
            // 把输入的文本转为二维码
            BitMatrix martix = null;// 宽度,高度
            try {
                martix = writer.encode(text, BarcodeFormat.QR_CODE,
                        QR_WIDTH, QR_HEIGHT);
            } catch (WriterException e) {
                e.printStackTrace();
            }
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix bitMatrix = new QRCodeWriter().encode(text,
                    BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
            int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
            for (int y = 0; y < QR_HEIGHT; y++) {
                for (int x = 0; x < QR_WIDTH; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * QR_WIDTH + x] = 0xff000000;
                    } else {
                        pixels[y * QR_WIDTH + x] = 0xffffffff;
                    }
                }
            }
            bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
                    Bitmap.Config.ARGB_8888);

            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return bitmap;
    }




    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
        /*
        移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
        联通：130、131、132、152、155、156、185、186
        电信：133、153、180、189、（1349卫通）
        总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
        */
        String telRegex = "[1][3,5,7,8]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }






    /**
     * 加载本地图片
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }





    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    //压缩图片
    public static Bitmap small(Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postScale(0.5f, 0.5f); //长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
        return resizeBmp;
    }
    //指定大小对图片进行压缩

    public static Drawable resizeImage(Bitmap bitmap, int w, int h)
    {
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        float n=scaleHeight>scaleWidth?scaleHeight:scaleWidth;

        Matrix matrix = new Matrix();
        matrix.postScale(n, n);
        // if you want to rotate the Bitmap
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return new BitmapDrawable(resizedBitmap);
    }




    /**
     * 读取图片属性：旋转的角度
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree  = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }





   public static  Bitmap  adjustPhotoRotation(Bitmap bm, final int orientationDegree)
    {

        Matrix m = new Matrix();
        m.setRotate(orientationDegree, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
        float targetX, targetY;
        if (orientationDegree == 90) {
            targetX = bm.getHeight();
            targetY = 0;
        } else {
            targetX = bm.getHeight();
            targetY = bm.getWidth();
        }

        final float[] values = new float[9];
        m.getValues(values);

        float x1 = values[Matrix.MTRANS_X];
        float y1 = values[Matrix.MTRANS_Y];

        m.postTranslate(targetX - x1, targetY - y1);

        Bitmap bm1 = Bitmap.createBitmap(bm.getHeight(), bm.getWidth(), Bitmap.Config.ARGB_8888);

        Paint paint = new Paint();
        Canvas canvas = new Canvas(bm1);
        canvas.drawBitmap(bm, m, paint);


        return bm1;
    }











    /**

     * 截屏

     * @param activity

     * @return

     */

    public static Bitmap captureScreen(Activity activity) {

        // 获取屏幕大小：

        DisplayMetrics metrics = new DisplayMetrics();

        WindowManager WM = (WindowManager) activity

                .getSystemService(Context.WINDOW_SERVICE);

        Display display = WM.getDefaultDisplay();

        display.getMetrics(metrics);

        int height = metrics.heightPixels; // 屏幕高

        int width = metrics.widthPixels; // 屏幕的宽

        // 获取显示方式

        int pixelformat = display.getPixelFormat();

        PixelFormat localPixelFormat1 = new PixelFormat();

        PixelFormat.getPixelFormatInfo(pixelformat, localPixelFormat1);

        int deepth = localPixelFormat1.bytesPerPixel;// 位深

        byte[] piex = new byte[height * width * deepth];

        try {

            Runtime.getRuntime().exec(

                    new String[] { "/system/bin/su", "-c",

                            "chmod 777 /dev/graphics/fb0" });

        } catch (IOException e) {

            e.printStackTrace();

        }

        try {

            // 获取fb0数据输入流

            InputStream stream = new FileInputStream(new File(

                    "/dev/graphics/fb0"));

            DataInputStream dStream = new DataInputStream(stream);

            dStream.readFully(piex);

        } catch (Exception e) {

            e.printStackTrace();

        }

        // 保存图片

        int[] colors = new int[height * width];

        for (int m = 0; m < colors.length; m++) {

            int r = (piex[m * 4] & 0xFF);

            int g = (piex[m * 4 + 1] & 0xFF);

            int b = (piex[m * 4 + 2] & 0xFF);

            int a = (piex[m * 4 + 3] & 0xFF);

            colors[m] = (a << 24) + (r << 16) + (g << 8) + b;

        }

        // piex生成Bitmap

        Bitmap bitmap = Bitmap.createBitmap(colors, width, height,

                Bitmap.Config.ARGB_8888);

        return bitmap;

    }










    public static void saveImageToGallery(Context context, Bitmap bmp,String path) {
        // 首先保存图片
        File appDir = new File(Constans.PIC_SHARE);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(path);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
    }




    //联网请求
    public static String executeGet(String url) throws Exception {
        BufferedReader in = null;

        String content = null;
        try {
            // 定义HttpClient
            HttpClient client = new DefaultHttpClient();
            // 实例化HTTP方法
            HttpGet request = new HttpGet(url);
//            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);

            in = new BufferedReader(new InputStreamReader(response.getEntity()
                    .getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            content = sb.toString();
        }catch (Exception e){
            LogUtils.log_E("utils失败信息："+e.getMessage());
            e.printStackTrace();

        }finally {
            if (in != null) {
                try {
                    in.close();// 最后要关闭BufferedReader
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return content;
        }
    }





    /**
     *
     * @param imgPath
     * @param bitmap
     * @param imgFormat 图片格式
     * @return
     */
    public static String imgToBase64(String imgPath, Bitmap bitmap,String imgFormat) {
        if (imgPath !=null && imgPath.length() > 0) {
            bitmap = readBitmap(imgPath);
        }
        if(bitmap == null){
            //bitmap not found!!
        }
        ByteArrayOutputStream out = null;
        try {
            out = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

            out.flush();
            out.close();

            byte[] imgBytes = out.toByteArray();
            return Base64.encodeToString(imgBytes, Base64.DEFAULT);
        } catch (Exception e) {
            return null;
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static Bitmap readBitmap(String imgPath) {
        try {
            return BitmapFactory.decodeFile(imgPath);
        } catch (Exception e) {
            return null;
        }

    }


















}
